package com.dnjn.mes.biz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dnjn.mes.biz.domain.*;
import com.dnjn.mes.biz.assist.ext.Wrapperz;
import com.dnjn.mes.biz.enums.DataType;
import com.dnjn.mes.biz.mapper.MesExceptMapper;
import com.dnjn.mes.biz.service.*;
import com.dnjn.mes.common.utils.CountModbusAddrUtil;
import com.dnjn.mes.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 异常编码表 服务实现类
 * </p>
 *
 * @author Amber
 * @since 2023-07-26
 */
@Service
public class MesExceptServiceImpl extends ServiceImpl<MesExceptMapper, MesExcept> implements IMesExceptService {
    @Autowired
    protected IMesWorkpieceService workpieceService;

    @Autowired
    protected IMesAssemblyService assemblyService;

    @Autowired
    private IMesExceptPlanXrefService exceptPlanXrefService;

    @Autowired
    private IMesResolvePlanService planService;

    @Autowired
    private IMesEquipmentService mesEquipmentService;

    @Override
    public String importData(List<MesExcept> list, boolean updateSupport) throws Exception {

        MesEquipment mesEquipment = mesEquipmentService.getOne(Wrapperz.lambdaQuery(MesEquipment.class).eq(MesEquipment::getEquipmentName, list.get(0).getEquipmentName()));
        if (null == mesEquipment) {
            throw new Exception("机器为空,查询失败!");
        }
        List<String> stringList = list.stream().map(MesExcept::getAssemblyName).distinct().collect(Collectors.toList());
        for (String name : stringList) {
            name = StringUtils.trimStr(name);
            MesAssembly assembly = assemblyService.getOne(Wrapperz.lambdaQuery(MesAssembly.class).eq(MesAssembly::getAssemblyName, name));
            if (null == assembly) {
                MesAssembly mesAssembly = new MesAssembly();
                mesAssembly.setAssemblyName(name);
                mesAssembly.setEquipmentId(mesEquipment.getEquipmentId());
                Integer assemblyOrdinal = assemblyService.getMaxOrdinal();
                assemblyOrdinal++;
                mesAssembly.setOrdinal(assemblyOrdinal);
                assemblyService.save(mesAssembly);
            }
        }
        for (MesExcept vo : list) {
            if(StringUtils.isEmpty(vo.getAddrPlc())){
                throw new Exception("请检查plc地址!");
            }
            vo.setAssemblyName(StringUtils.trimStr(vo.getAssemblyName()));
            MesAssembly assembly = assemblyService.queryByCrumb(vo.getEquipmentName(), vo.getAssemblyName());
            vo.setAssemblyId(assembly.getAssemblyId());
            //计算modbus地址和type
            if (StringUtils.isNotEmpty(vo.getAddrPlc())) {
                //设置datatype
                if (vo.getAddrPlc().contains(".")) {
                    String split = vo.getAddrPlc().split("\\.")[1];
                    int parseInt = Integer.parseInt(split);
                    switch (parseInt) {
                        case 0:
                            vo.setDataType(DataType.BIT0);
                            break;
                        case 1:
                            vo.setDataType(DataType.BIT1);
                            break;
                        case 2:
                            vo.setDataType(DataType.BIT2);
                            break;
                        case 3:
                            vo.setDataType(DataType.BIT3);
                            break;
                        case 4:
                            vo.setDataType(DataType.BIT4);
                            break;
                        case 5:
                            vo.setDataType(DataType.BIT5);
                            break;
                        case 6:
                            vo.setDataType(DataType.BIT6);
                            break;
                        case 7:
                            vo.setDataType(DataType.BIT7);
                            break;
                        default:
                            throw new RuntimeException("设置dataType失败，请检查plc地址： " + vo.getAddrPlc());
                    }
                } else {
                    vo.setDataType(DataType.BIT0);
                    vo.setAddrPlc(vo.getAddrPlc() + ".0");
                }

                long count = baseMapper.selectCount(
                        Wrappers.<MesExcept>lambdaQuery().eq(MesExcept::getAddrPlc, vo.getAddrPlc()));
                if (count > 0) {
                    continue;
                }

                Integer modbusAddrByPlcAddr = CountModbusAddrUtil.getExceptModbusAddrByPlcAddr(vo.getAddrPlc());
                vo.setAddrModbus(modbusAddrByPlcAddr);
            }
            vo.setEquipmentId(mesEquipment.getEquipmentId());
            save(vo);
//            saveOrUpdate(vo, Wrapperz.lambdaQuery(MesExcept.class)
//                    .eq(MesExcept::getAssemblyId, assembly.getAssemblyId())
//                    .eq(MesExcept::getAddrPlc, vo.getAddrPlc())
//            );
        }
        return "OK";

    }

    @Override
    public List<MesExcept> selectExceptList(MesExcept domain) {
        return baseMapper.selectExceptList(domain);
    }

    @Override
    @Transactional
    public int deledtExceptById(Long exceptId) {
        QueryWrapper<MesExceptPlanXref> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("except_id", exceptId);
        List<Long> planIdList = exceptPlanXrefService.list(queryWrapper).stream().map(MesExceptPlanXref::getPlanId).collect(Collectors.toList());
        //删除异常与方案关联,先删除关联关系！
        boolean remove = exceptPlanXrefService.remove(Wrapperz.lambdaQuery(MesExceptPlanXref.class).eq(MesExceptPlanXref::getExceptId, exceptId));

        if (!planIdList.isEmpty()) {
            for (Long aLong : planIdList) {
                //删除异常下的方案列表
                planService.removePlanById(aLong);
            }
        }
        return baseMapper.removeExceptById(exceptId);
    }

    @Override
    public List<MesExcept> getExceptPageByAssemblyId(Long assemblyId) {
        List<MesExcept> exceptList = baseMapper.getExceptPageByAssemblyId(assemblyId);
        for (MesExcept mesExcept : exceptList) {
            List<MesResolvePlan> planList = exceptPlanXrefService.getPlanListByExceptId(mesExcept.getExceptId());
            mesExcept.setPlanList(planList);
        }
        return exceptList;
    }

    @Override
    public String getDescriptionByExceptId(Long exceptId) {
        return baseMapper.getDescriptionByExceptId(exceptId);
    }

    @Override
    public List<MesResolvePlan> getPlansByExceptId(Long exceptId, long equipmentId) {
        return baseMapper.getPlansByExceptId(exceptId,equipmentId);
    }
}
